/***************************************************************************
 *   This is a part of the NextCAD Web APP.                                *
 *   Copyright (C) AMCAX, All rights reserved.                             *
 ***************************************************************************/

import { pickedLineData } from '@amcax/base';
import {
  NumberInputFormat,
  PickInputRJSFFormat,
} from '@app-cad/common/components/command-form/constants';
import { PickableCommandForm } from '@app-cad/common/components/command-form/pickable';
import { useCommand } from '@app-cad/common/hooks/useCommand';
import { useTools } from '@app-cad/common/hooks/useTools';
import { CurvedBaseCommand, CurvedCmdDialogParams } from '@app-cad/types';
import { RJSFSchema } from '@rjsf/utils';
import { useAsyncEffect } from 'ahooks';
import i18n from 'i18next';
import { useEffect, useState } from 'react';

type FormData = { curve?: pickedLineData; angular: number; deviation: number };

type Params = {
  curve: string;
  angular: number;
  deviation: number;
};

// 曲线光顺
function CommandSmooth({ title, onClose, props }: CurvedCmdDialogParams) {
  const initData = {
    angular: 0.05,
    deviation: 0.01,
  };
  const [formData, setFormData] = useState<FormData>(initData);

  const { picker } = useTools();

  useAsyncEffect(async () => {
    if (props == null) {
      setFormData(initData);
      return;
    }

    const params: Params = props.params;
    const { curve, angular, deviation } = params;

    await initEditDependency([curve]);

    setFormData({
      curve: picker.generatePickObjByPickID(curve) as pickedLineData,
      angular,
      deviation,
    });
  }, [props?.shape]);

  const isFormDataValid = () => {
    const { curve, angular, deviation } = formData;
    return curve != null && angular != null && deviation != null;
  };

  const checkAndFinishDraw = async () => {
    if (!isFormDataValid()) {
      return;
    }

    await execute(false);

    onClose();
  };

  const { initEditDependency, initingEdit, clear, confirmCommand, isLoading } =
    useCommand('cmd-smooth', {
      commandName: 'CreateCurve',
      editDxid: props?.shape,
      onClose,
      finishDraw: checkAndFinishDraw,
    });

  useEffect(() => {
    if (!isFormDataValid()) {
      clear();
      return;
    }

    execute(true);
  }, [formData]);

  const execute = (preview: boolean) => {
    const { curve, angular, deviation } = formData;

    return confirmCommand(
      {
        type: 'Smooth',
        a: {
          curve: curve.edgeId,
          angular,
          deviation,
        } as Params,
      },
      preview,
    );
  };

  const schema: RJSFSchema = {
    type: 'object',
    properties: {
      curve: {
        type: 'string',
        format: PickInputRJSFFormat.PickCurve,
      },
      angular: {
        type: 'number',
        title: '相切阈值',
        format: NumberInputFormat.Angle,
      },
      deviation: {
        type: 'number',
        title: '最大偏差',
        format: NumberInputFormat.Length,
      },
    },
  };

  return (
    <PickableCommandForm
      disabled={initingEdit}
      onClose={onClose}
      title={title}
      schema={schema}
      formData={formData}
      submitLoading={isLoading}
      onChange={(v) => {
        setFormData(v);
      }}
      extraUiSchema={{
        curve: {
          'ui:placeholder': '请输入曲线',
          'ui:autofocus': true,
        },
      }}
      submitText='完成'
      onSubmit={checkAndFinishDraw}
      noValidate
      isFormDataValid={isFormDataValid()}
    />
  );
}

export const cmdSmooth: CurvedBaseCommand = {
  id: 'CommandSmooth',
  label: 'command.smooth',
  icon: 'commands/curved/smooth-curve',
  create: (label, onClose, props) => (
    <CommandSmooth
      title={i18n.t(label)}
      onClose={onClose}
      props={props}
    />
  ),
};
